<?php

class HyMemberController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='/layouts/newmember';

	/**
	 * @return array action filters
	 */
/*	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}*/
	
	public function actions()    {
 
         return array(
             'captcha'=>array(
                'class'=>'CCaptchaAction',
                 'backColor'=>0xFFFFFF,  //背景颜色
                 //'minLength'=>4,  //最短为4位
                 //'maxLength'=>4,   //是长为4位
                'transparent'=>true,  //显示为透明，当关闭该选项，才显示背景颜色
             ),
          );
      }
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
            array('allow',  // allow all users to perform 'index' and 'view' actions
		    'actions'=>array('index','view','login','captcha'),
		    'users'=>array('*'),
		   ),

         	array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new HyMember;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		
		if(isset($_POST['HyMember']))
		{
			$model->attributes=$_POST['HyMember'];
             
			if($model->save())
				$this->redirect(array('view','id'=>$model->user_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['HyMember']))
		{
			$model->attributes=$_POST['HyMember'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->user_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
	
		$dataProvider=new CActiveDataProvider('HyMember');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new HyMember('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['HyMember']))
			$model->attributes=$_GET['HyMember'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return HyMember the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
			
		$model=HyMember::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param HyMember $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='hy-member-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
	
	public function actionLogin(){
	  	$model = new HyMember('login');
 		//$this->performAjaxValidation($model);
		if(isset($_POST['HyMember']))
		{
			$model->attributes = $_POST['HyMember'];
			
			if($model->validate()){ 
				//Yii::app()->user->setFlash('ok','恭喜您，验证完成！'); 
			
				$username = $_POST['HyMember']['user_name'];
				$password = $_POST['HyMember']['user_pws'];
				
				$criteria = new CDbCriteria( ) ; 

				$criteria -> condition = ' (user_name  = :username or user_email  = :username) and user_pws = :user_pws ' ; 
	            $criteria -> params = array(':username' => $username,':user_pws' => $password) ; 
	            
			    $member = HyMember::model()->find($criteria) ; 
			    if($member){
			    	
			    	Yii::app()->session['username'] = $member->user_name;
			    	Yii::app()->session['userpws']  = $member->user_name;	 
			    	Yii::app()->session['user_id']  = $member->user_id;;
			    	
			    	$this->redirect(array('Member'));
			    } else {
			    	$this->popup('账号或密码错误！');
			    }
			    
			    $this->refresh(); 
				
			} 
			
			if($model->save())
				$this->redirect(array('view','id'=>$model->user_id));
		}

		$this->render('login',array(
			'model'=>$model,
		));
	}
	
	public function actiondoreg() {
		
	  // 验证验证码
	    $yancode = Yii::app()->request->getParam('yancode');
		$this->yancode($yancode);
		
		$post=new HyMember;
		$times = date("YmdHis",time());		
		$post->user_email = Yii::app()->request->getParam('user_email');
		$post->user_pws = Yii::app()->request->getParam('user_pws');
		
		
		
		$post->user_regtime = $times;
		$post->user_regip = $_SERVER['REMOTE_ADDR'];
		
		
		if($post->save()){
			   $this->popup('恭喜您，注册成功！,请登陆');
			}else{
				$this->popup("对不起，注册 失败，请稍候再试！");
			}
		}
	
	
	/**
	 * 注册 进入验证
	 *
	 */
	public function actionDologin(){
		
		$username = Yii::app()->request->getParam('username');
		$password = Yii::app()->request->getParam('password');
		$yancode  = Yii::app()->request->getParam('yancode');
		$action   = Yii::app()->request->getParam('action');
		
		// 验证验证码
		$this->yancode($yancode);

		if($action == "login"){
			$criteria = new CDbCriteria( ) ; 
		    $criteria -> condition = ' (user_name  = :username or user_email  = :username) and user_pws = :user_pws ' ; 
            $criteria -> params = array(':username' => $username,':user_pws' => $password) ; 

            $member = HyMember::model()->find($criteria) ; 
		    if($member){
		    	Yii::app()->session['username'] = $member->user_name;
		    	Yii::app()->session['userpws']  = $member->user_name;	 
		    	Yii::app()->session['user_id']  = $member->user_id;;
		    	$this->redirect(array('Member'));
		    }else{
		    	$this->popup('账号或密码错误！');
		    }
		    die;
		} else {
			die("非法进入");
		}
		
	}
	
	/**
	 *  安全退出
	 */
	public  function actionQuit(){
	   Yii::app()->session->clear(); 
	   Yii::app()->session->destroy();
	   $this->popup('安全退出！','./');
	}
	
	/**
	 * 注册
	 */
	public function actionReg(){
		
		if(empty($_GET['render']) || $_GET['render'] == 'reg'){ 
		   $_GET['render'] = 'reg';  
		   $model = new HyMember('reg');
		} elseif($_GET['render'] == 'toreg'){
		   $model = new HyMember('toreg');
		} elseif($_GET['render'] == 'mobilereg'){
		   $model = new HyMember('mobilereg');
		} 
		
	//	$model -> reg();
		//$this->performAjaxValidation($model);
	
		if(isset($_POST['HyMember'])){

			$array   = $_POST['HyMember'];
			$delarr  = array('rePws','verifyCode');
		//	$autoArr = $this->unsetArray($array, $delarr);
			$model->attributes = $array;
		    $model->user_regtime  = date("YmdHis",time());	
		    $model->user_regip    = $_SERVER['REMOTE_ADDR'];
		    $model->user_intro    = "";
		  //  print_r($model->attributes);
		    
		    if($model->validate()) {
		    	if($model->save()){
		    		$criteria = new CDbCriteria( ) ; 
			    	$criteria -> select   ='user_id,user_name'; 
			    	$criteria -> limit    ='1'; 
					$criteria -> order    = ' user_id desc ' ; 
					
				    $member = HyMember::model()->find($criteria) ;  
				    Yii::app()->session['username'] = $member->user_name.$member->user_mobile.$member->user_email;
			    	//Yii::app()->session['userpws']  = $member->user_name;	 
				    Yii::app()->session['user_id']  = $member->user_id;;
			    	$this->redirect(array('Member'));
				} else {
				    	$this->popup("对不x起，注册失败，请稍候再试！");
				}
			}
		}
		$this->render($_GET['render'],array(
			'model'=>$model,
		));
	}
	
	/**
	 * 会员中心页
	 */
	public function actionMember() {
		$this->layout = '//layouts/column2';
		$this->isLogin();//验证是否登陆
		
		$id = Yii::app()->session['user_id'];
		$model=HyMember::model()->findByPk($id);

	    if(isset($_POST['user_email']))
		{
			$model->attributes = $_POST;
			if($model->save()) $this->redirect(array('member'));
		}
		
		$this->render('member',array(
			'model'=>$model,
		));
		
		
		$this->render('member');
	}
	
	/**
	 *  我的订单
	 *
	 */
	public function actionMyOrder(){
		$this->layout = '//layouts/column2';
		
		$this->isLogin();//验证是否登陆
		
		
			$dataProvider=new CActiveDataProvider('HyBor',array(
		   'criteria'=>array(
		        'condition'=>'memberID='.Yii::app()->session['user_id'],
		       // 'order'=>'PublishDate DESC',
		       // 'with'=>array('author'),
		    ),
		    'pagination'=>array(
		        'pageSize'=>20,
		    ),
		));
	
		$this->render('myOrder',array(
			'dataProvider'=>$dataProvider,
		));
		
	}
	
	
	/**
	 *  我的账户
	 */
    public function actionAccount(){
    	$this->layout = '//layouts/column2';
        $this->isLogin();//验证是否登陆
    	$this->render('account');
	}

	/**
	 * 发布产品 
	 *
	 */
	public function actionAddPro() {
		
			$model=new HyBSysProducts;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['HyBSysProducts']))
		{
			$model->attributes=$_POST['HyBSysProducts'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->SysProductsID));
		}

		$this->render('addpro',array(
			'model'=>$model,
		));
		
	}
	
	
    /**
	 * 管理产品 
	 *
	 */
	public function actionProMan() {
			$this->isLogin();//验证是否登陆
			$dataProvider=new CActiveDataProvider('HyBor',array(
		   'criteria'=>array(
		        'condition'=>'memberID='.Yii::app()->session['user_id'],
		       // 'order'=>'PublishDate DESC',
		       // 'with'=>array('author'),
		    ),
		    'pagination'=>array(
		        'pageSize'=>10,
		    ),
		));
	
		$this->render('proman',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	public function actionIntegrate() {
		$this->layout = '//layouts/column2';
		
		$this->render('integrate');
		
	}
	
	/**
	 * 
	 * 发送邮件端
	 */
    public function mail(){
		$member['email'] = $this->member_model->getEmails();
		$name       = $this->input->post('name');     //
		$title      = $this->input->post('title');     //
		$content    = $this->input->post('content');     //
		
		$arr = array(
		  'name' => $name,
		  'title' =>$title,
		  'content'=>$content,
		);
		
		$curlPost      = $this->handleUrl($arr);
		if(!empty($name) ){
		    $url = "http://www.4007798866.com//php-email/";
		    
	    	$ch   = curl_init();                                 //初始化curl  
		    curl_setopt($ch, CURLOPT_URL, $url);                          //提交到指定网页  
		    curl_setopt($ch, CURLOPT_HEADER, 0);                          //设置header  
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);                  //要求结果为字符串且输出到屏幕上  
		    curl_setopt($ch, CURLOPT_POST, 1);                            //post提交方式  
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); 
		    $data = curl_exec($ch);                                       //运行curl  
		    curl_close($ch); 
			
			$arr = $this->manageData($data);
			if($arr['b'] == "200"){
				$this->popup('successfully');
				exit();
			} else {
				$this->popup('send_failed');
				exit();
			} 
		}
		
		$this->load->view('admin/header_view', $this->data);
		$this->load->view('admin/mail',$member);
		$this->load->view('admin/footer_view');
	}
	
	/**
	 * 
	 * 发送 短信端
	 * @param String $tel  
	 * @param Int $sms
	 */
    public function actionDuanxin($tel,$sms){
		
		$arr = array(
		  'username' => USERNAME,  //用户名
		  'Password' => PASSWORD,  //用户密码
		  'tel'      => $tel,      //发送目标号码（多个号码以”|”分隔，单次提交号码不得超过1W条，例：1376462XXXX|1376462XXXX|1376462XXXX）
		  'sms'      => $sms,      //短信内容（内容不能超过70个字符）
		);
		
	    $curlPost      = $this->handleUrl($arr);
	
		if(!empty($name) ){
		    $url = "http://218.242.44.53:9999/sendsms.aspx";
	    	$ch = curl_init();                                 //初始化curl  
		    curl_setopt($ch, CURLOPT_URL, $url);               //提交到指定网页  
		    curl_setopt($ch, CURLOPT_HEADER, 0);               //设置header  
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);       //要求结果为字符串且输出到屏幕上  
		    curl_setopt($ch, CURLOPT_POST, 1);                 //post提交方式  
		    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); 
		    $data = curl_exec($ch);                            //运行curl  
		    curl_close($ch); 
			
		 	 $msgArr = array(
		    	'0'   =>'成功',
		        '-1'  =>'失败',
		        '-2'  =>'缺少目标号码',
		        '-3'  =>'缺少用户名或密码', 
		    	'-4'  =>'缺少短信内容',
		        '-5'  =>'登陆失败',
		        '-6'  =>'存在非法字符',
		        '-7'  =>'存在错误号码', 
		    	'-8'  =>'余额不足',
		        '-9'  =>'服务器连接失败',
		        '-10' =>'服务器连接失败',
		        '-11' =>'短信内容存在系统保留关键词',
		        '-12' =>'号码条数超出限制',
		        '-13' =>'短信内容长度超出', 
		    );
		    
		    foreach ($msgArr as $key=>$value){
		      if($key == $data){
		    		$this->popup($value);
		    	}
		    }
		}
	}
	
	
    /**
	 * curl处理返回结果字符串
	 * @param String $arr
	 * @return Array $arr
	 */
	function manageData($str){
		$arr = explode('&',$str);
	    if($arr){
		    foreach ($arr  as $value) {
		    	$secarr = explode("=", $value);
		    	$newarr[$secarr[0]] =$secarr[1]; 
		    }
	    }
	    return $newarr;
   }

	
}
